package com.hillky.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hillky.springboot.controller.request.BaseRequest;
import com.hillky.springboot.entity.Category;
import com.hillky.springboot.mapper.CategoryMapper;
import com.hillky.springboot.service.CategoryService;
import com.hillky.springboot.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> list(){
        return categoryMapper.list();
    }

    @Override
    public PageInfo<Category> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<Category> categories = categoryMapper.listByCondition(baseRequest);
        return new PageInfo<>(categories);
    }

    @Override
    public void save(Category category) {
        categoryMapper.save(category);
    }

    @Override
    public Category getById(Integer id) {
        Category category=categoryMapper.getById(id);
        return category;
    }

    @Override
    public void update(Category category) {
        category.setUpdateTime(new Date());
        categoryMapper.update(category);
        return;
    }

    @Override
    public void deleteById(Integer id) {
        categoryMapper.deleteById(id);
        return;
    }

    @Override
    public List<Category> getOptions() {
        List<Category> list = this.list();
        // 生成菜单树
        return createTree(null, list);
    }

    private List<Category> createTree(Integer pid,List<Category> categories){
        List<Category> treeList = new ArrayList<>();
        for (Category category : categories) {
            if (pid == null) {
                if (category.getPid() == null) {  // 那这就是第一级节点
                    treeList.add(category);
                    category.setChildren(createTree(category.getId(), categories));
                }
            } else {
                if (pid.equals(category.getPid())) {
                    treeList.add(category);
                    category.setChildren(createTree(category.getId(), categories));
                }
            }
            if (CollUtil.isEmpty(category.getChildren())) {
                category.setChildren(null);
            }
        }
        return treeList;
    }
}
